# -*- coding:utf-8 -*-
from scapy.all import *
cnt=0
APList={}
#接受到指定类型包的所有设备，但不是只要接受到了该设备就被攻击
devdic={}
#Deauth攻击
deauthAttackdic={}
#Disassociation攻击
disassociationAttackdic={}
authAttackdic={}
#AuthAttack攻击
authAttackTimes=0
#统计每种类型的帧数量
timeout=5
lastAuthAttackNum=0

def PacketHandler(packet):
    if packet.haslayer(Dot11Deauth):
        destmac=packet.addr1
        srcmac=packet.addr2
        bssidman=packet.addr3
        if destmac in deauthAttackdic:
            deauthAttackdic[destmac]+=1
        else:
            devdic[destmac]=1
            deauthAttackdic[destmac]=1
    if packet.haslayer(Dot11Auth):
        destmac = packet.addr1
        srcmac = packet.addr2
        bssidman = packet.addr3

        global authAttackTimes
        authAttackTimes += 1;

        if destmac in authAttackdic:
            authAttackdic[destmac] += 1
        else:
            devdic[destmac] = 1
            authAttackdic[destmac] = 1
    if packet.haslayer(Dot11Disas):
        destmac=packet.addr1
        srcmac=packet.addr2
        bssidman=packet.addr3
        if destmac in disassociationAttackdic:
            disassociationAttackdic[destmac]+=1
        else:
            devdic[destmac]=1
            disassociationAttackdic[destmac]=1
    if packet.haslayer(Dot11Beacon):
        print(packet.addr2,packet.SC)


print('the program is running ,please wait...')

# cap = sniff(offline='DisassociationAttack.pcapng', prn=lambda x:x.summary())

while(True):
    devdic={}
    deauthAttackdic={}
    disassociationAttackdic={}
    authAttackdic={}
    authAttackTimes=0
    cap = sniff(iface="wlp2s0", prn=PacketHandler,timeout=timeout)
    print('device number is',len(devdic))
    for k,v in devdic.items():
        #print('dev is',k)
        destmac=k
        if (destmac in disassociationAttackdic):
            if disassociationAttackdic[destmac] > timeout:
                print('[+]Disassociation attack found,the victim is',destmac)
        if(destmac in deauthAttackdic):
            if deauthAttackdic[destmac]>timeout*80:
                print('[+]Deauth attack found,the victim is ',destmac)

    if(authAttackTimes>50*timeout):
        print('[+]Auth attack found')
    print('current scan is done,the next will begin')
    print('--------------------------------------------------------------')